package cn.wolfcode.wolf2world.resolver;

import cn.wolfcode.wolf2world.domain.UserInfo;
import cn.wolfcode.wolf2world.redis.service.UserRedisService;
import cn.wolfcode.wolf2world.web.annotation.UserParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户对象解析器
 * @author 杨兴健
 * @Date 2020/8/15 11:34
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserRedisService userRedisService;

    /**
     * 判断参数是否符合条件，符合则执行resolveArgument方法
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == UserInfo.class && parameter.hasParameterAnnotation(UserParam.class);
    }

    /**
     * 执行对象注入到spring容器管理
     * @param parameter
     * @param mavContainer
     * @param webRequest
     * @param binderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        return userRedisService.getCurrentUser(token);
    }
}
